import { IconFont } from "@/components/IconFont";
import { MenuDataItem } from "@/constants";
import { useMainStore } from "@/stores";
import { Menu } from "antd";
import { ReactNode, useMemo } from "react";
import { useLocation, useNavigate } from "react-router-dom";

interface MenuInfo {
  key: string;
  keyPath: string[];
}
interface MenuItem {
  key: string;
  label: string;
  icon: string | ReactNode;
  children?: MenuItem[];
}

const SiderContent: React.FC = () => {
  const navigate = useNavigate();
  const { pathname } = useLocation();
  const { collapsed, menuTree, keyPath, setKeyPath } = useMainStore((state) => state);
  const openKeys = keyPath.length > 1 ? keyPath.slice(0, keyPath.length - 1) : [];
  const logoClassName = `logoContainer ${collapsed ? "logoCollapsed" : ""}`;

  // 菜单渲染
  const renderMenuItem = (routes: MenuDataItem[]) => {
    const results: MenuItem[] = [];
    routes.forEach((route) => {
      const { path, title, icon, children } = route;
      const item: MenuItem = {
        key: path,
        label: title,
        icon: icon ? <IconFont type={icon} /> : ""
      };

      if (children && children.length > 0) {
        item.children = renderMenuItem(children);
      }
      results.push(item);
    });

    return results;
  };
  // 菜单数据
  const items = useMemo(() => {
    return renderMenuItem(menuTree);
  }, [menuTree]);

  // 菜单点击事件
  const handleMenuClick = (item: MenuInfo) => {
    const newkeyPath = [...item.keyPath].reverse();
    setKeyPath(newkeyPath); // 存储正序的keyPath
    navigate(item.key);
  };

  return (
    <div>
      <div className={logoClassName} onClick={() => navigate("/home")}>
        <img
          style={{ width: "20px", marginLeft: "18px" }}
          src="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg"
        />
        <h4 style={{ marginLeft: "8px" }}>Ant Design Admin</h4>
      </div>
      <div className="menuContainer">
        <Menu
          mode="inline"
          items={items}
          defaultOpenKeys={openKeys}
          selectedKeys={[pathname]}
          onClick={handleMenuClick}
        ></Menu>
      </div>
    </div>
  );
};

export default SiderContent;
